﻿using System;
using System.Windows;
using System.Threading;
using System.Collections.Generic;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
//
using ScheduleMVVM.Model.RuntimeFramework;
using ScheduleMVVM.Agent.Localization;

namespace ScheduleMVVM.Agent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private static volatile bool _classInitialized;

        /// <summary>
        /// Application context
        /// </summary>
        RuntimeContext Context = new RuntimeContext();
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        public ScheduledAgent()
        {
            if (!_classInitialized)
            {
                _classInitialized = true;
                // Subscribe to the managed exception handler
                Deployment.Current.Dispatcher.BeginInvoke(delegate
                {
                    Application.Current.UnhandledException += ScheduledAgent_UnhandledException;
                });
            }
        }

        /// Code to execute on Unhandled Exceptions
        private void ScheduledAgent_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //Code to perform your task in background
            Dictionary<RouteEntry, DataAccess> dictionary = new Dictionary<RouteEntry, DataAccess>();
            Boolean downloadInitiated = false;
            // Download timetable
            foreach (var i in Context.Favourites)
            {
                DataAccess accessor = new DataAccess(i);
                if ((accessor.SourceTimeStamp.DayOfYear < DateTime.Today.DayOfYear || accessor.SourceTimeStamp.Year < DateTime.Today.Year) && !downloadInitiated)
                {
                    accessor.Refresh();
                    downloadInitiated = true;
                }
                dictionary.Add(i, accessor);
            }
            UpdateTiles(dictionary);
            if(downloadInitiated) Thread.Sleep(60 * 1000); // Wait for downloaders to finish their job
            //
            NotifyComplete();
        }

        private void UpdateTiles(Dictionary<RouteEntry, DataAccess> dictionary)
        {
            foreach (var i in ShellTile.ActiveTiles)
            {
                // Skip main app tile
                if (i.NavigationUri.OriginalString == "/") continue;
                var entry = ParseTile(i);
                var tileData = new StandardTileData()
                {
                    Title = entry.Title,
                    Count = 0,
                    BackgroundImage = new Uri("/Background.png", UriKind.Relative),
                };
                if (dictionary[entry].NextUp != String.Empty)
                {
                    tileData.BackTitle = entry.Title;
                    tileData.BackContent = dictionary[entry].NextUp;
                }
                i.Update(tileData);
            }
        }
        private RouteEntry ParseTile(ShellTile Tile)
        {
            var Uri = Tile.NavigationUri;
            Int32 StartStationId = Int32.Parse(Uri.OriginalString.Split('?')[1].Split('&')[0].Split('=')[1]);
            Int32 EndStationId = Int32.Parse(Uri.OriginalString.Split('?')[1].Split('&')[1].Split('=')[1]);
            return Context.GetFavouriteEntry(StartStationId, EndStationId);
        }
    }
}